package com.avic.rong.shoppingCar.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.R;
import com.avic.rong.activity.product.DetailProductActivity;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.shoppingCar.api.ShoppingCarGoodsKuCunApi;
import com.avic.rong.shoppingCar.api.ShoppingCarUpDateCartNumApi;
import com.avic.rong.shoppingCar.bean.ShoppingCarListBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.bumptech.glide.Glide;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.util.List;

/**
 * Created by Chenjiaxin on 2019/7/12 09:43
 * E-Mail Address：16601203965@163.com
 */
public class ShoppingCarRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private LayoutInflater inflater;
    private Context context;
    private ShoppingCarListBean bean = new ShoppingCarListBean();
    public DeleteItem deleteItem;

    private static final int ItemShouQin = 0;
    private static final int ItemYouHuo = 1;
    private static int currentType = 0;
    private int currentItem = -1;
    boolean oneJia = false;
    private List<ShoppingCarListBean.CartListBean> cartList;


    public DeleteItem getDeleteItem() {
        return deleteItem;
    }

    public void setDeleteItem(DeleteItem deleteItem) {
        this.deleteItem = deleteItem;
    }

    public ShoppingCarRvAdapter(Context context) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    public void setBean(ShoppingCarListBean bean) {
        this.bean = bean;
        cartList = bean.getCartList();
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
//        if (bean.getCartList().get(position).getGoods().getIsOnSale() == 1) {
//            currentType = ItemYouHuo;
//        } else {
//            currentType = ItemShouQin;
//        }
        try {
            switch (cartList.get(position).getGoods().getIsOnSale()) {
                case 0:
                    currentType = ItemShouQin;
                    break;
                case 2:
                    currentType = ItemShouQin;
                    break;
                case 1:
                    currentType = ItemYouHuo;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentType;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        //有货item
        View view1 = inflater.inflate(R.layout.view_message_rv_item, viewGroup, false);
        //售罄item
        View view2 = inflater.inflate(R.layout.view_message_rv_item1, viewGroup, false);
        if (getItemViewType(i) == ItemYouHuo)
            return new ShoppingCarRvViewHolder(view1);
        else
            return new ShoppingCarShouQingRvViewHolder(view2);
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {
        final double prices = FigureUpPrice();
        deleteItem.showPrice(prices);
        //售罄
        if (viewHolder instanceof ShoppingCarShouQingRvViewHolder) {
            ShoppingCarShouQingRvViewHolder holder1 = (ShoppingCarShouQingRvViewHolder) viewHolder;
            final View finalView = holder1.itemView;
            double price = FigureUpPrice();
            deleteItem.showPrice(price);
            holder1.title.setText(cartList.get(i).getGoods().getGoodsName());
            //设置img

            if (StringUtils.isEmpty(cartList.get(i).getGoods().getGoodsImg())) {
                holder1.img.setVisibility(View.GONE);
                holder1.goods_text1.setVisibility(View.VISIBLE);
                holder1.goods_name1.setText(cartList.get(i).getGoods().getCatName());
                holder1.goods_keyword1.setText(cartList.get(i).getGoods().getKeywords());
            } else {
                if (cartList.get(i).getGoods().getGoodsImg().contains("rongrong.")) {
                    Glide.with(context).load(cartList.get(i).getGoods().getGoodsImg()).into(holder1.img);
                } else {
                    Glide.with(context).load(bean.getBiaoZhunImg() + cartList.get(i).getGoods().getGoodsImg()).into(holder1.img);
                }
            }

            //点击收藏按钮
            holder1.collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "收藏", Toast.LENGTH_SHORT).show();
                    ((SwipeMenuLayout) (finalView)).quickClose();
                }
            });
            //点击删除按钮
            holder1.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((SwipeMenuLayout) (finalView)).quickClose();
//                    deleteItem.delete(i);
                }
            });
            //item长按
            holder1.ll_root.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    deleteItem.longClick();
                    return false;
                }
            });
        } else {
            //有货
            final ShoppingCarRvViewHolder holder = (ShoppingCarRvViewHolder) viewHolder;
            final View finalView = holder.itemView;


            if (cartList.get(i).getGoods().getBasicAttrList().size() == 0) {
                holder.status.setVisibility(View.GONE);
                holder.xiaoguo.setVisibility(View.GONE);
            } else {
                holder.status.setText(cartList.get(i).getGoods().getBasicAttrList().get(0).getAttrValue());
                holder.xiaoguo.setText(cartList.get(i).getGoods().getBasicAttrList().get(0).getAttrValue());
            }


            holder.tv_Title.setText(cartList.get(i).getGoods().getGoodsSn() + " " + cartList.get(i).getGoods().getGoodsName());
            holder.tv_Num.setText(cartList.get(i).getGoodsNumber() + "");
            Log.e("cjx", "goodsNumber:" + cartList.get(i).getGoodsNumber());
            final double price = FigureUpPrice();
            deleteItem.showPrice(price);
            int skuId = cartList.get(i).getSkuId();
            if (cartList.get(i).getGoods().getGoodsSkuList().get(0).getSkuAttrList().size() > 0) {
                holder.sku_layout.setVisibility(View.VISIBLE);
                for (int k = 0; k < cartList.get(i).getGoods().getGoodsSkuList().size(); k++) {
                    int skuListId = cartList.get(i).getGoods().getGoodsSkuList().get(k).getSkuId();
                    if (skuId == skuListId) {
                        holder.tv_SelectText.setText(cartList.get(i).getGoods().getGoodsSkuList().get(k).getSkuName());
                        holder.tv_Price.setText("¥" + cartList.get(i).getGoods().getGoodsSkuList().get(k).getShopPrice());
                    }
                }
            } else {
                holder.sku_layout.setVisibility(View.GONE);
            }

//            JSONArray jsonArray = null;
//                String skuName = "";
//            if (cartList.get(i).getGoods().getSkuName() != null) {
//                if (!cartList.get(i).getGoods().getSkuName().equals("")) {
//                 skuName = cartList.get(i).getGoods().getSkuName();
//                boolean goodJson = isGoodJson(skuName);
//                if (goodJson){
//                    try {
//                        jsonArray = new JSONArray(cartList.get(i).getGoods().getSkuName());
//                        for (int j = 0; j < jsonArray.length(); j++) {
//                            JSONObject jsonObject = (JSONObject) jsonArray.get(j);
//                            Iterator<String> keys = jsonObject.keys();
//                            String key = "";
//                            while (keys.hasNext()) {//遍历JSONObject
//                                key = (String) keys.next().toString();
//                                if (null != key && !"".equals(key)) {
//                                    String value = (String) jsonObject.get(key);
//                                    skuName = key + ": " + value;
//                                }
//                            }
//                        }
//                    } catch(JSONException e){
//                        e.printStackTrace();
//                    }
//                    holder.tv_SelectText.setText(skuName);
//                }else{
//                    holder.tv_SelectText.setText(skuName);
//                }}else{
//                    holder.goodsskuimg.setVisibility(View.GONE);
//                    holder.tv_SelectText.setVisibility(View.GONE);
//                    holder.sku_layout.setVisibility(View.GONE);
//                }
//                }else{
//                holder.sku_layout.setVisibility(View.GONE);
//                holder.goodsskuimg.setVisibility(View.GONE);
//                holder.tv_SelectText.setVisibility(View.GONE);
//            }
            holder.img_selectButton.setSelected(cartList.get(i).isIsSelect());
            //设置img
            if (StringUtils.isEmpty(cartList.get(i).getGoods().getGoodsImg())) {

                holder.img.setVisibility(View.GONE);
                holder.goods_text.setVisibility(View.VISIBLE);
                holder.hengxian.setVisibility(View.VISIBLE);
                holder.goods_name.setText(cartList.get(i).getGoods().getCatName());
                holder.goods_keyword.setText(cartList.get(i).getGoods().getKeywords());
            } else {
                holder.goods_text.setVisibility(View.GONE);
                holder.hengxian.setVisibility(View.GONE);
                holder.img.setVisibility(View.VISIBLE);
                String goodsImg = cartList.get(i).getGoods().getGoodsImg();
                if (cartList.get(i).getGoods().getGoodsImg().contains("rongrong.")) {
                    Glide.with(context).load(goodsImg).placeholder(R.mipmap.common_bg).into(holder.img);
                } else {
                    Glide.with(context).load(bean.getBiaoZhunImg() + goodsImg).placeholder(R.mipmap.common_bg).into(holder.img);
                }
            }


            //长按item
            holder.ll_root.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    deleteItem.longClick();
                    return false;
                }
            });


            boolean selectAll = isSelectAll();
            deleteItem.selectALL(selectAll);
            isSelectAll();
            holder.img_selectButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cartList.get(i).isIsSelect()) {
                        cartList.get(i).setIsSelect(false);
                        holder.img_selectButton.setSelected(false);
                    } else {
                        cartList.get(i).setIsSelect(true);
                        holder.img_selectButton.setSelected(true);
                    }
                    double price = FigureUpPrice();
                    deleteItem.showPrice(price);
                    boolean isSelectAll = isSelectAll();
                    deleteItem.selectALL(isSelectAll);
                }
            });
            //点击收藏按钮
            holder.btn_Collect.setOnClickListener(new ItemOperationClickListener(cartList.get(i).getGoods(), holder.itemView, i, 1));
            holder.btn_Collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((SwipeMenuLayout) (finalView)).quickClose();
                    deleteItem.collect(cartList.get(i).getGoods(), i);
                    notifyDataSetChanged();
                }
            });
            holder.btn_Delete.setOnClickListener(new ItemOperationClickListener(cartList.get(i).getGoods(), holder.itemView, i, 2));
            //点击删除按钮
            holder.btn_Delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((SwipeMenuLayout) (finalView)).quickClose();
                    deleteItem.delete(cartList.get(i).getGoods(), i);
                    notifyDataSetChanged();
                }
            });
            holder.tv_Title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int goodsId = cartList.get(i).getGoods().getSkuId();
                    context.startActivity(DetailProductActivity.getIntent(context, goodsId + ""));
                }
            });
            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int goodsId = cartList.get(i).getGoods().getSkuId();
                    context.startActivity(DetailProductActivity.getIntent(context, goodsId + ""));
                }
            });
            holder.goods_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int goodsId = cartList.get(i).getGoods().getSkuId();
                    context.startActivity(DetailProductActivity.getIntent(context, goodsId + ""));
                }
            });

//            item长按
            holder.ll_root.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    deleteItem.longClick();
                    return true;
                }
            });

            //减
            holder.btn_Jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int num = cartList.get(i).getGoodsNumber();
                    if (num <= 1) {
                        Toast.makeText(context, "最少要有一個商品", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        num--;
                        int cartId = cartList.get(i).getCartId();
                        cartList.get(i).setGoodsNumber(num);
                        holder.tv_Num.setText(num + "");
                        updateCartNum(num, cartId);
                        double price = FigureUpPrice();
                        deleteItem.showPrice(price);
                    }
                }

            });
            //加

            holder.btn_Jia.setOnClickListener(new View.OnClickListener() {

                private int num = 0;

                @Override
                public void onClick(View v) {
                    /**
                     * 需要做请求当前数量的操作
                     */
                    num = cartList.get(i).getGoodsNumber();
                    //  ToastTools.showLongToast(context,"GoodsNumber:"+ num);
                    int skuId = cartList.get(i).getSkuId();
                    SharedPreferencesUtil.getInstance().put("biao", i);
                    getKuCun(num, skuId);

                }
            });


            //sku
            holder.tv_SelectText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteItem.skuPop(i);
                }
            });
        }
    }


    //获取商品库存
    private void getKuCun(int num, int skuId) {
        ShoppingCarGoodsKuCunApi goodsKuCunApi = new ShoppingCarGoodsKuCunApi((ShoppingCarActivity) context, httpOnNextListener, num, skuId);
        goodsKuCunApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(goodsKuCunApi);
    }

    //判断库存
    HttpOnNextListener httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            int i = SharedPreferencesUtil.getInstance().getAsInt("biao", 0);
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                Toast.makeText(context, "商品库存不足", Toast.LENGTH_SHORT).show();

            } else {
                int num = cartList.get(i).getGoodsNumber();
                int cartId = cartList.get(i).getCartId();
                num++;
                cartList.get(i).setGoodsNumber(num);
                double price = FigureUpPrice();
                deleteItem.showPrice(price);
                updateCartNum(num, cartId);
                notifyItemChanged(i);

            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };


    public static boolean isGoodJson(String json) {

        try {
            new JsonParser().parse(json);
            return true;
        } catch (JsonParseException e) {
            System.out.println("bad json: " + json);
            return false;
        }
    }

    //判断是否全部选中
    private boolean isSelectAll() {
        for (int i = 0; i < cartList.size(); i++) {
            if (!cartList.get(i).isIsSelect()) {
                return false;
            } else {
                continue;
            }
        }
        return true;
    }

    @Override
    public int getItemCount() {
        return cartList.size();
    }

    class ShoppingCarShouQingRvViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        LinearLayout goods_text1;
        TextView title, delete, collect, goods_name1, goods_keyword1, seletextname, status;
        LinearLayout ll_root;

        public ShoppingCarShouQingRvViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.message_img_Img1);
            title = itemView.findViewById(R.id.message_tv_Title1);
            delete = itemView.findViewById(R.id.message_btn_delete1);
            collect = itemView.findViewById(R.id.message_btn_collect1);
            goods_text1 = itemView.findViewById(R.id.message_goods_text1);
            goods_name1 = itemView.findViewById(R.id.message_goods_name1);
            goods_keyword1 = itemView.findViewById(R.id.message_goods_keyword1);
            seletextname = itemView.findViewById(R.id.message_tv_SelectText);
            status = itemView.findViewById(R.id.tv_standard_status);
            ll_root = itemView.findViewById(R.id.ll_root);
        }
    }


    public class ItemOperationClickListener implements View.OnClickListener {

        ShoppingCarListBean.CartListBean.GoodsBean goodsBean;
        View itemView;
        int type = 0;
        int position = 0;

        public ItemOperationClickListener(ShoppingCarListBean.CartListBean.GoodsBean goodsBean, View itemView, int position, int type) {
            this.goodsBean = goodsBean;
            this.itemView = itemView;
            this.type = type;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            ((SwipeMenuLayout) itemView).quickClose();

            if (deleteItem != null) {
                switch (type) {
                    case 1:
                        deleteItem.collect(goodsBean, position);
                        break;
                    case 2:
                        deleteItem.delete(goodsBean, position);
                        break;

                    case 3:

                        break;
                }


            }
        }
    }

    public interface DeleteItem {
        void delete(ShoppingCarListBean.CartListBean.GoodsBean goodsBean, int index);//删除

        void collect(ShoppingCarListBean.CartListBean.GoodsBean goodsBean, int index);//收藏

        void skuPop(int index);//sku

        void longClick();//长按

        void showPrice(double price);//刷新价格

        void selectALL(boolean so);

//        void isSelectAll(boolean flag);

    }

    public double FigureUpPrice() {
        double price = 0;
        if (cartList != null) {
            for (int i = 0; i < cartList.size(); i++) {
                int skuId = cartList.get(i).getSkuId();
                if (cartList.get(i).getGoods().getIsOnSale() ==1 ) {
                    if (cartList.get(i).isIsSelect()) {
                        for (int k = 0; k < cartList.get(i).getGoods().getGoodsSkuList().size(); k++) {
                            int skuListId = cartList.get(i).getGoods().getGoodsSkuList().get(k).getSkuId();
                            if (skuId == skuListId) {
                                int goodsNumber = cartList.get(i).getGoodsNumber();
                                double shopPrice = cartList.get(i).getGoods().getGoodsSkuList().get(k).getShopPrice();
                                price += goodsNumber * shopPrice;
                            }
                        }
                    }
                }
            }

            return price;
        }
        return 0;
    }

    //更新商品数量
    private void updateCartNum(int num, int cartId) {
        ShoppingCarUpDateCartNumApi upDateCartNumApi = new ShoppingCarUpDateCartNumApi((ShoppingCarActivity) context, updateCartNumListener, num, cartId);
        upDateCartNumApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(upDateCartNumApi);
    }

    //更新商品数量监听
    HttpOnNextListener updateCartNumListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                Log.e("cjx", subjects.getMsg());
                return;
            }
            Log.e("cjx", "商品数量更新完成");

        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "更新商品数量" + e.getMessage());
        }
    };

}

class ItemClickListener implements View.OnClickListener {

    private ShoppingCarRvViewHolder holder;
    private List<ShoppingCarListBean.CartListBean> cartList;
    private int i;
    private Context context;
    private int currentNum = 0;
    private int currentIndex = 0;
    private ShoppingCarRvAdapter adapter;

    public ItemClickListener(ShoppingCarRvViewHolder holder, List<ShoppingCarListBean.CartListBean> cartList, int i, Context context, ShoppingCarRvAdapter adapter) {
        this.holder = holder;
        this.cartList = cartList;
        this.i = i;
        this.context = context;
        this.adapter = adapter;
    }

    @Override
    public void onClick(View v) {
        int num = cartList.get(i).getGoodsNumber();
        currentNum = ++num;
        currentIndex = i;
        cartList.get(i).setGoodsNumber(currentIndex);
        adapter.notifyDataSetChanged();
        getKuCun(num, cartList.get(i).getSkuId());
    }

    //获取商品库存
    private void getKuCun(int num, int skuId) {
        ShoppingCarGoodsKuCunApi goodsKuCunApi = new ShoppingCarGoodsKuCunApi((ShoppingCarActivity) context, simpleOnNextListener1, num, skuId);
        goodsKuCunApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(goodsKuCunApi);
    }

    HttpOnNextListener simpleOnNextListener1 = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (subjects.getCode().equals("0000")) {
                holder.tv_Num.setText(cartList.get(currentIndex).getGoodsNumber() + "");
                double price = adapter.FigureUpPrice();
                adapter.deleteItem.showPrice(price);
                adapter.notifyDataSetChanged();
            } else {
                ToastTools.showLongToast(context, "商品库存不足");
            }
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "错误：" + e.getMessage());
        }
    };

}
